package com.anxin.act.task.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.anxin.act.task.dao.WfCommentStagingDao;
import com.anxin.act.task.entity.WfCommentStaging;
import com.anxin.act.task.vo.FormPropertyVo;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.web.service.BaseService;
import com.anxin.common.utils.SecurityUtils;
import com.anxin.sys.system.entity.SysUser;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 流程审批意见暂存Service业务层处理
 *
 * @author jbs
 * @date 2022-11-10
 */
@Service
public class WfCommentStagingService extends BaseService<WfCommentStagingDao, WfCommentStaging>{
    @Autowired
    private WfCommentStagingDao wfCommentStagingDao;


    /**
     * 暂存审批意见
     * @param taskVo
     */
    public void saveByTaskVo(TaskVo taskVo){
        // 删除之前暂存的记录
        wfCommentStagingDao.deleteByTaskId(taskVo.getId(), UserUtils.getUser().getId());
        List<FormPropertyVo> formFieldList = taskVo.getFormFieldList();
        for (FormPropertyVo formPropertyVo : formFieldList) {
            this.saveByFormPropertyVo(taskVo,formPropertyVo);
        }

    }


    /**
     * 暂存审批意见
     */
    public void saveByFormPropertyVo(TaskVo taskVo,FormPropertyVo formPropertyVo){
        WfCommentStaging wfCommentStaging = new WfCommentStaging();
        wfCommentStaging.setActId(taskVo.getActId());
        wfCommentStaging.setTaskId(taskVo.getTaskId());
        wfCommentStaging.setFieldName(formPropertyVo.getId());
        wfCommentStaging.setValue(formPropertyVo.getValue());
        this.save(wfCommentStaging);
    }

    /**
     * 加载暂存的审批意见
     * @param taskVo
     */
    public void loadingByTaskBy(TaskVo taskVo){
        List<WfCommentStaging> wfCommentStagingList = wfCommentStagingDao.findByTaskId(taskVo.getId(), UserUtils.getUser().getId());
        if (wfCommentStagingList.size() > 0){
            Map<String,String> wfCommentStagingMap = new HashMap<>();
            for (WfCommentStaging wfCommentStaging : wfCommentStagingList) {
                wfCommentStagingMap.put(wfCommentStaging.getFieldName(),wfCommentStaging.getValue());
            }

            if (taskVo.getFormFieldList() != null){
                for (FormPropertyVo formPropertyVo : taskVo.getFormFieldList()) {
                    formPropertyVo.setValue(wfCommentStagingMap.get(formPropertyVo.getId()));
                }
            }
        }

    }



    /**
     * 保存流程审批意见暂存
     *
     * @param wfCommentStaging 流程审批意见暂存
     * @return 结果
     */
    public int save(WfCommentStaging wfCommentStaging){
        return super.save(wfCommentStaging);
    }


    /**
     * 删除流程审批意见暂存信息
     *
     * @param id 流程审批意见暂存ID
     * @return 结果
     */
    public int deleteById(String id){
        SysUser user = SecurityUtils.getUser();
        return wfCommentStagingDao.deleteById(id,user.getId());
    }
}
